<template>
  <div class="earlyWarning-container" v-loading.fullscreen.lock="fullscreenLoading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
    <container-item title="主动预警" hasNav>
      <div style="width: 100%; height: 100%" v-if="showWeb == 0">
        <div class="top">
          <div class="fanhui-btn">
            <i  @click="$router.push('/')" class="el-icon-arrow-left"></i>
            <span  @click="$router.push('/')">返回</span>
            <span class="title_box">{{ $route.query.site }}</span>
          </div>
          <menu-element />
        </div>
        <div class="content">
          <sec-container title="正极换流阀子模块状态">
            <template slot="zhuangtai">
              <!-- 0运行中 2是已停运 -->
              <div class="yunxingzhong_style" v-if="qiaobiStatus.zheng === 0">
                <div class="dui"></div>
                运行中
              </div>
              <div class="yitingyun_style" v-else-if="qiaobiStatus.zheng === 2">
                <div class="cuo"></div>已停运
              </div>
              <div class="zhanwei_style" v-else>--</div>
            </template>
            <div class="qiaobi-state-wrapper" v-if="$route.query.site === '阜康换流站'">
              <qiaobi-status v-for="item in zheng" class="qiaobi-item" :key="item.name" :normal="item.normal"
                :error="item.t0" :abnormal="item.t1" :leakList="item.points" :name="item.name" :state="item.state"
                @qiaobiClick="
                  qiaobiClick($route.query.site, '正极', item.name)
                  "></qiaobi-status>
            </div>
            <div class="qiaobi-state-wrapper" v-if="$route.query.site === '中都换流站'">
              <qiaobi-status-zhongdu v-for="item in zheng" class="qiaobi-item" :key="item.name" :normal="item.normal"
                :error="item.t0" :abnormal="item.t1" :leakList="item.points" :name="item.name" :state="item.state"
                @qiaobiClick="
                  qiaobiClick($route.query.site, '正极', item.name)
                  "></qiaobi-status-zhongdu>
            </div>

          </sec-container>
          <sec-container title="负极换流阀子模块状态">
            <template slot="zhuangtai">
              <!-- 0运行中 2是已停运 -->
              <div class="yunxingzhong_style" v-if="qiaobiStatus.fu === 0">
                <div class="dui"></div>运行中
              </div>
              <div class="yitingyun_style" v-else-if="qiaobiStatus.fu === 2">
                <div class="cuo"></div>已停运
              </div>
              <div class="zhanwei_style" v-else>--</div>
            </template>
            <div class="qiaobi-state-wrapper" v-if="$route.query.site === '阜康换流站'">
              <qiaobi-status v-for="item in fu" class="qiaobi-item" :key="item.name" :normal="item.normal"
                :error="item.t0" :abnormal="item.t1" :leakList="item.points" :name="item.name" :state="item.state"
                @qiaobiClick="
                  qiaobiClick($route.query.site, '负极', item.name)
                  "></qiaobi-status>
            </div>
            <div class="qiaobi-state-wrapper" v-if="$route.query.site === '中都换流站'">
              <qiaobi-status-zhongdu v-for="item in fu" class="qiaobi-item" :key="item.name" :normal="item.normal"
                :error="item.t0" :abnormal="item.t1" :leakList="item.points" :name="item.name" :state="item.state"
                @qiaobiClick="
                  qiaobiClick($route.query.site, '负极', item.name)
                  "></qiaobi-status-zhongdu>
            </div>
          </sec-container>
          <sec-container v-for="(item, key) in neishuilengList" :key="key" title="内水冷状态">
            <div class="qiaobi-wrapper">
              <div class="item">
                <h3>{{ key === 0 ? '正极' : '负极' }}换流阀</h3>
                <qiaobi v-for="(item1, index) in item" :key="index" class="qiaobi-item" :type="item1.name"
                  :state="item1.state" :control="key === 0 ? '正极' : '负极'" @qiaobiClick="neiShuiLengClick">
                </qiaobi>
                <!-- <qiaobi class="qiaobi-item" type="主循环流量" :state="item.zxhllState" :control="item.controlName"
                  @qiaobiClick="neiShuiLengClick">
                </qiaobi>
                <qiaobi class="qiaobi-item" type="进出阀温差" :state="item.jqfwcState" :control="item.controlName"
                  @qiaobiClick="neiShuiLengClick">
                </qiaobi> -->
              </div>
            </div>
          </sec-container>
          <!-- <sec-container title="内水冷状态">
            <div class="qiaobi-wrapper">
              <div class="item">
                <h3>负极换流阀</h3>
                <qiaobi v-for="(item, index) in fu.valveMeasureList" class="qiaobi-item" :key="index"
                  :type="item.measureName" :state="item.state" control="负极" @qiaobiClick="neiShuiLengClick"></qiaobi>
              </div>
            </div>
          </sec-container> -->
        </div>
      </div>
      <sonModule :stationName="stationName" :controlName="controlName" :bridgeName="bridgeName"
        :zhengfuValue="zhengfuValue" :qiaobiName="qiaobiName" v-if="showWeb == 1" @back="handleFanhui"></sonModule>

    </container-item>
    <pub-dialog title="内水冷历史数据" :top="'10vh'" :dialogVisible="dialog.visible" dialogVisableRef="dialogVisible"
      @switchVisable="switchVisable" @dialogCancel="dialogCancel" class="dialog" btnType="2">
      <el-form ref="form" :model="dialog.form" inline label-width="130px" class="form-search">
        <el-form-item>
          <el-date-picker style="width: 400px" v-model="dialog.form.date" start-placeholder="开始日期"
            end-placeholder="结束日期" type="datetimerange" :unlink-panels="true" value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select v-model="dialog.form.type" placeholder="请选择" collapse-tags>
            <el-option v-for="(item, index) in dialog.valveMeasureList" :key="item" :label="item" :value="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="btn-nav-bg stripe-btn" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="chart-box" v-loading="loadingShow" element-loading-background="rgba(0, 0, 0, 0.8)">
        <linebar style="width: 100%; height: 450px" :grid="grid" legendLeft="right" :rotate="-15"
          :axisLabelColor="'rgba(198,211,236)'" :datas="dialog.chartData.data" :xAxis="dialog.chartData.xAxis"
          :isShowTooltip="true"></linebar>
      </div>
    </pub-dialog>
  </div>
</template>

<script>
import ContainerItem from "@/components/ContainerItem.vue";
import SecContainer from "@/components/SecContainer";
import qiaobi from "./components/qiaobi.vue";
import qiaobiStatus from "./components/qiaobiStatus.vue";
import qiaobiStatusZhongdu from "./components/qiaobiStatusZhongdu.vue";
import sonModule from "./components/sonModule.vue";
import Linebar from "@/components/Linebar";
import MenuElement from "@/components/MenuElement/index.vue";
import {
  getXjSiteList,
  getDeviceList,
  getArm,
  getXJHistoryWaterWaveform,
  getWarnList,
  getZdyjRunZdTrend
} from "@/api/earlyWarning";
import PubDialog from "@/components/pubDialog.vue";
import { getZdyjApiZhongduQbList, getZdyjApiKangbaQbList, getZdyjRunKbTrend } from "@/api/zhongduApi";
import { cedian } from "@/assets/data";


export default {
  name: "Index",
  components: {
    MenuElement,
    PubDialog,
    ContainerItem,
    SecContainer,
    qiaobiStatus,
    qiaobiStatusZhongdu,
    qiaobi,
    sonModule,
    Linebar,
  },
  data() {
    return {
      // 正负极换流阀子模块状态 0: 运行中 2: 已停运 1: 占位符
      qiaobiStatus: {
        zheng: 1,
        fu: 1

      },
      loadingShow: false,
      fullscreenLoading: false,
      grid: {
        containLabel: true,
        left: "4%",
        top: "10%",
        right: "10%",
        bottom: "10%",
      },
      converterStationList: [],
      lockReconnect: false,
      showWeb: 0, // 是否显示子模块详细
      zheng: [],
      fu: [],
      neishuilengList: [],
      currentIdOfHis: "",
      currentIdOfsonModule: "",
      stationName: "",
      controlName: "",
      bridgeName: "",
      colSData: [
        { label: "测点名称", param: "label" },
        { label: "数量", param: "value" },
      ],
      tableHeight: 100,

      timer: new Date().getTime(),

      // 内水冷波形图
      dialog: {
        visible: false,
        form: {
          date: [
            this.$moment().subtract(2, "hours").format("YYYY-MM-DD HH:mm:ss"),
            this.$moment().format("YYYY-MM-DD HH:mm:ss"),
          ],
          type: 0,
          electrodeName: '正极'
        },
        valveMeasureList: [],
        chartData: {
          data: [
            {
              type: "line",
              name: "水冷膨胀罐",
              color: "#5087ec",
              showSymbol: true,
              smooth: true,
              data: [],
            },
            {
              type: "line",
              name: "阈值上限",
              color: "#35eb68",
              showSymbol: true,
              smooth: true,
              data: [],
            },
            {
              type: "line",
              name: "阈值下限",
              color: "rgba(84, 61, 7, 1)",
              showSymbol: true,
              smooth: true,
              data: [],
            },
          ],
          xAxis: [],
        },
      },
    };
  },
  // watch: {
  // '$route' (to, from) {
  //        // 要执行更新的代码
  //        this.calcHeight();
  //   this.init();
  //   this.initWebSocket();
  //   }
  // },

  created() {
    const sessionStorageData = sessionStorage.getItem('kangbafuye');
    if (sessionStorageData) {
      let { zhengfuValue, qiaobiName } = JSON.parse(sessionStorageData);
      this.showWeb = 1;
      this.zhengfuValue = zhengfuValue;
      this.qiaobiName = qiaobiName;
    }
    this.dialog.valveMeasureList = [...cedian]
    this.calcHeight();
    this.init();
    // this.initWebSocket();
  },
  destroyed: function () {
    // 离开页面生命周期函数
    // this.websocketOnclose();
  },
  mounted() { },
  methods: {
    handleFanhui() {
      this.showWeb = 0;
      sessionStorage.removeItem('kangbafuye');
    },
    calcHeight() {
      this.tableHeight = window.innerHeight - 730;
    },
    // 换流站列表
    getXjSiteListFun() {
      getXjSiteList().then((res) => {
        this.converterStationList = res.data;
        try {
          if (Array.isArray(res.data) && res.data.length) {
            this.getDeviceListData(res.data[0].id, res.data[0].site);
          }
        } catch (err) {
          throw new Error(err);
        }
      });
    },
    init() {
      this.getDeviceListData();
    },
    qiaobiClick(s, t, n) {
      this.showWeb = 1;
      this.zhengfuValue = t;
      this.qiaobiName = n;
      sessionStorage.setItem('kangbafuye', JSON.stringify({
        zhengfuValue: t,
        qiaobiName: n,
      }))
      // this.currentIdOfsonModule = s + t + n;
      // this.stationName = s;
      // this.controlName = t;
      // this.bridgeName = n;
    },

    // 设备台账
    async getDeviceListData() {

      let fun;
      if (this.$route.query.site === '阜康换流站') {
        fun = getDeviceList;
      } else if (this.$route.query.site === '中都换流站') {
        fun = getZdyjApiZhongduQbList;
      } else {
        fun = getZdyjApiKangbaQbList;
      }
      this.fullscreenLoading = true;
      let res = await fun();
      if (res.code == 200) {
        let arr0 = [];
        let arr1 = [];
        let indexName = this.$route.query.site === '阜康换流站' ? '6' : this.$route.query.site === '中都换流站' ? '8' : '4';
        console.log(indexName)
        res.data.forEach((item) => {
          if (item.electrodeName === '正极') {
            this.qiaobiStatus.zheng = item.lockState;
            arr0 = item.qb;
            arr0.forEach(element => {
              let qbPointsArr = [];
              element.points.forEach(elementPoints => {
                // 1. 判断是否是重复的

                let str = elementPoints.name.substr(0, indexName);
                console.log(str)
                let strHou = elementPoints.name.substr(indexName, elementPoints.name.length - 4);

                let idx = qbPointsArr.findIndex(item => item.groupName === str);
                if (idx !== -1) { // 添加到数组中
                  qbPointsArr[idx].values.push({
                    name: strHou,
                    state: elementPoints.state,
                  });
                } else {// 不是重复的 新建数组 添加到数组中
                  qbPointsArr.push({
                    groupName: str,
                    values: [{
                      name: strHou,
                      state: elementPoints.state,
                    }]
                  });
                }
              });
              if (this.$route.query.site === '中都换流站') {

                // 确保数组长度至少为3
                if (qbPointsArr.length >= 3) {
                  let temp = qbPointsArr[1]; // 保存第二位元素
                  qbPointsArr[1] = qbPointsArr[2];   // 将第三位元素移动到第二位
                  qbPointsArr[2] = temp;    // 将保存的第二位元素移动到第三位
                }

              }
              element.points = qbPointsArr;
            });

          } else if (item.electrodeName === '负极') {
            this.qiaobiStatus.fu = item.lockState;
            arr1 = item.qb;
            arr1.forEach(element => {
              let qbPointsArr = [];
              element.points.forEach(elementPoints => {

                // 1. 判断是否是重复的
                let str = elementPoints.name.substr(0, indexName);
                let strHou = elementPoints.name.substr(indexName, elementPoints.name.length - 4);

                let idx = qbPointsArr.findIndex(item => item.groupName === str);
                if (idx !== -1) { // 添加到数组中
                  qbPointsArr[idx].values.push({
                    name: strHou,
                    state: elementPoints.state,
                  });
                } else {// 不是重复的 新建数组 添加到数组中
                  qbPointsArr.push({
                    groupName: str,
                    values: [{
                      name: strHou,
                      state: elementPoints.state,
                    }]
                  });
                }
              });
              if (this.$route.query.site === '中都换流站') {

                // 确保数组长度至少为3
                if (qbPointsArr.length >= 3) {
                  let temp = qbPointsArr[1]; // 保存第二位元素
                  qbPointsArr[1] = qbPointsArr[2];   // 将第三位元素移动到第二位
                  qbPointsArr[2] = temp;    // 将保存的第二位元素移动到第三位
                }

              }
              element.points = qbPointsArr;

            });

          }
        });
        console.log(arr0)
        console.log(arr1)

        this.zheng = arr0;
        this.fu = arr1;
        this.neishuilengList = [res.data[0].sl, res.data[1].sl]
      } else {
        console.log(res.msg)
      }
      this.fullscreenLoading = false;

    },

    // 监听弹窗关闭
    switchVisable(visable, ref) {
      this[ref] = visable;
    },
    // 关闭弹窗
    dialogCancel() {
      this.dialog.visible = false;
    },
    // 内水冷点击
    neiShuiLengClick(data) {
      this.dialog.visible = true;
      this.dialog.form.type = cedian.indexOf(data.type);
      this.dialog.form.electrodeName = data.control;
      let params = {
        electrodeName: data.control,
        endTime: this.dialog.form.date[1],
        startTime: this.dialog.form.date[0],
        locationName: this.$route.query.site === '康巴换流站' ? '康巴诺尔站' : this.$route.query.site,
        sample: cedian.indexOf(data.type),
      };
      this.getXJHistoryWaterWaveformData(params);
    },
    // 内水冷弹出查询
    handleSearch(data) {
      let params = {
        electrodeName: this.dialog.form.electrodeName,
        endTime: this.dialog.form.date[1],
        startTime: this.dialog.form.date[0],
        locationName: this.$route.query.site === '康巴换流站' ? '康巴诺尔站' : this.$route.query.site,
        sample: this.dialog.form.type,
      };
      this.getXJHistoryWaterWaveformData(params);
    },
    // 内水冷波形图
    getXJHistoryWaterWaveformData(params) {
      this.loadingShow = true;
      let API;
      if (this.$route.query.site === '阜康换流站') {
        API = getXJHistoryWaterWaveform;
      } else if (this.$route.query.site === '中都换流站') {
        API = getZdyjRunZdTrend;
      } else {
        API = getZdyjRunKbTrend;
      }
      API(params).then((res) => {
        this.loadingShow = false;
        if (res.code == 200) {
          this.dialog.chartData.xAxis = res.data.map((item) => item.time);
          this.dialog.chartData.data[0].data = res.data.map(
            (item) => item.value
          );
          this.dialog.chartData.data[0].name = this.dialog.valveMeasureList[this.dialog.form.type]
          this.dialog.chartData.data[1].data = res.data.map(
            (item) => item.upperLimit
          );
          this.dialog.chartData.data[2].data = res.data.map(
            (item) => item.lowerLimit
          );
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.top {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #fff;

  .fanhui-btn {
    cursor: pointer;

    span {
      margin-left: 5px;
    }
  }

  .lujing {
    margin-left: 50px;
  }
}

::v-deep .el-radio-group {
  margin-bottom: 10px;
}

::v-deep .el-radio-button__inner {
  background: #101d29;
  border: 0;
  color: #ffffff;
}

::v-deep .el-radio-button:first-child .el-radio-button__inner {
  border: 0;
}

::v-deep .sec-title-right {
  margin-top: 15px !important;
}

.content {
  width: 100%;
  height: calc(100% - 42px);
  display: flex;
  justify-content: space-between;
  align-content: space-between;
  flex-wrap: wrap;

  ::v-deep .sec-wrapper {
    width: calc(50% - 8px);

    &:first-child,
    &:nth-child(2) {
      height: calc(80% - 8px);
    }

    &:nth-child(3),
    &:nth-child(4) {
      height: calc(20% - 8px);
    }

    &:last-child {
      .sec-content {
        position: relative;
      }
    }
  }

  .qiaobi-state-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;

    .qiaobi-item {
      width: 33.3%;
      height: calc(100% / 2);
    }
  }

  .qiaobi-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;

    .item {
      display: flex;
      flex: 1;
      align-items: center;

      h3 {
        align-self: center;
        width: 100px;
        color: #40e5f0;
      }
    }

    .qiaobi-item {
      width: 33.3%;
      height: calc(100% - 20px);
    }
  }
}

.earlyWarning-container {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
}

::v-deep .el-descriptions {
  .el-descriptions__body {
    color: #fff;
    font-size: 16px;
    line-height: 50px;
    background-color: transparent;

    .el-descriptions-item__cell {
      padding-bottom: 30px;

      .el-descriptions-item__content {
        color: rgb(80, 229, 239);
      }
    }
  }
}

.yunxingzhong_style {
  width: 86px;
  height: 26px;
  background: #074919;
  border-radius: 13px;
  border: 1px solid #156727;
  font-family: PingFang SC;
  font-weight: bold;
  font-size: 16px;
  color: #FFFFFF;
  background: linear-gradient(1deg, #17B23D 0%, #BBF8CF 100%);
  background-clip: text;
  -webkit-text-fill-color: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10px;
}

.dui {
  width: 14px;
  height: 14px;
  background: url('~@/assets/images/home/dui.png') no-repeat center center;
  background-size: 100% 100%;
  margin-right: 8px;
}

.cuo {
  width: 14px;
  height: 14px;
  background: url('~@/assets/images/home/cuo.png') no-repeat center center;
  background-size: 100% 100%;
  margin-right: 8px;
}

.yitingyun_style {
  width: 86px;
  height: 26px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #6C1D19;
  border-radius: 13px;
  border: 1px solid #9A332E;
  background: linear-gradient(1deg, #E37067 0%, #EFD5D6 100%);
  background-clip: text;
  -webkit-text-fill-color: transparent;
  font-family: PingFang SC;
  font-weight: bold;
  font-size: 16px;
   margin-left: 10px;
}

.zhanwei_style {
  color: #fff;
}
.title_box{
  font-family: PingFang SC;
  font-weight: bold;
  font-size: 24px;
  color: #F1FFFF;
}
</style>
